package practise;

import java.util.*;

public class TopKFrequent {
    public List<String> topKFrequent(String[] words, int k) {
        // 1. 先统计
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if(map.get(word) != null) {
                map.put(word, map.get(word) + 1);
            } else {
                map.put(word, 1);
            }
        }
        // 2. 创建优先级队列
        PriorityQueue<Map.Entry<String, Integer>> minHeap = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                int compare = o1.getValue().compareTo(o2.getValue());
                return compare == 0 ? o2.getKey().compareTo(o1.getKey()) : compare;
            }
        });
        for(Map.Entry<String, Integer> entry : map.entrySet()) {
            if(minHeap.size() < k) {
                minHeap.offer(entry);
            } else {
                Map.Entry<String, Integer> top = minHeap.peek();
                int compare = top.getValue().compareTo(entry.getValue());
                if(compare < 0) {
                    // 出现频率比较小
                    minHeap.poll();
                    minHeap.offer(entry);
                } else if(compare == 0 && top.getKey().compareTo(entry.getKey()) > 0) {
                    minHeap.poll();
                    minHeap.offer(entry);
                }
            }
        }

        // 3. 放入链表内
        List<String> list = new LinkedList<>();
        for (int i = 0; i < k; i++) {
            list.add(0, minHeap.poll().getKey());
        }

        // 4. 返回
        return list;
    }
}
